package com.aliyun.messagemgt.application.service.sms.impl;

import com.aliyun.messagemgt.application.service.sms.SmsStatisticsService;
import com.aliyun.messagemgt.util.SmsQuotaDateUtils;
import com.aliyun.messagemgt.common.constants.SmsTrendConstant;
import com.aliyun.messagemgt.dto.vo.SmsTrendQueryVO;
import com.aliyun.messagemgt.dto.vo.SmsTrendResultVO;
import com.aliyun.messagemgt.domain.repository.MsgHandleLogRepository;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author byp
 * @date 2020/7/31
 */
@Service
public class SmsStatisticsServiceImpl implements SmsStatisticsService {

    @Autowired
    private MsgHandleLogRepository msgHandleLogMapper;

    private static Logger logger = LoggerFactory.getLogger(SmsStatisticsServiceImpl.class);

    @Override
    public SmsTrendResultVO trend(SmsTrendQueryVO smsTrendQueryVO) {
        SmsTrendResultVO resultVO = new SmsTrendResultVO();
        List<SmsTrendResultVO.SmsTrend> smsTrendList;
        String beginDate;
        //记录表中的结束时间
        String endDate;
        //生成临时表的结束日期
        String tempEndDate;
        if (StringUtils.isEmpty(smsTrendQueryVO.getMsgSourceId()) && smsTrendQueryVO.getQueryType() == null) {
            //为空的话。最近15天全部短信渠道消息源的推送数据
            logger.info("smsQueryVO必要查询条件为空，查询最近15天全部短信渠道消息源的推送数据");
            beginDate = SmsQuotaDateUtils.before15Day();
            endDate = SmsQuotaDateUtils.tomorrowFormat(new Date());
            tempEndDate = SmsQuotaDateUtils.dateFormatDay(new Date());
            smsTrendList = msgHandleLogMapper.queryDayTrend(null, beginDate, endDate, tempEndDate);
        } else {
            logger.info("查询条件不为空");
            switch (smsTrendQueryVO.getQueryType()) {
                case SmsTrendConstant.TREND_QUERY_TYPE_DAY_15:
                    //最近15天
                    logger.info("查询最近15天");
                    beginDate = SmsQuotaDateUtils.before15Day();
                    //SQL查询统计包含今天，因为格式化为yyyy-MM-dd <=无法查询今天的数据
                    endDate = SmsQuotaDateUtils.tomorrowFormat(new Date());
                    tempEndDate = SmsQuotaDateUtils.dateFormatDay(new Date());
                    smsTrendList = msgHandleLogMapper.queryDayTrend(smsTrendQueryVO.getMsgSourceId(), beginDate, endDate, tempEndDate);
                    break;
                case SmsTrendConstant.TREND_QUERY_TYPE_DAY_30:
                    //最近30天
                    logger.info("查询最近30天");
                    beginDate = SmsQuotaDateUtils.before30Day();
                    endDate = SmsQuotaDateUtils.tomorrowFormat(new Date());
                    tempEndDate = SmsQuotaDateUtils.dateFormatDay(new Date());
                    smsTrendList = msgHandleLogMapper.queryDayTrend(smsTrendQueryVO.getMsgSourceId(), beginDate, endDate, tempEndDate);
                    break;
                case SmsTrendConstant.TREND_QUERY_TYPE_MONTH_12:
                    //最近12个月
                    logger.info("查询最近12个月");
                    beginDate = SmsQuotaDateUtils.before12MonthDay();
                    endDate = SmsQuotaDateUtils.dateFormatDay(new Date());
                    smsTrendList = msgHandleLogMapper.queryMonthTrend(smsTrendQueryVO.getMsgSourceId(), beginDate, endDate, 12);
                    break;
                case SmsTrendConstant.TREND_QUERY_TYPE_SELF_DEFINING:
                    //自定义时间段
                    int days = SmsQuotaDateUtils.diffDays(smsTrendQueryVO.getBeginTime(), smsTrendQueryVO.getEndTime());
                    if (days > SmsTrendConstant.MARGIN_DAY) {
                        logger.info("事件间隔大于90天，按月查询");
                        beginDate = SmsQuotaDateUtils.dateFormatDay(smsTrendQueryVO.getBeginTime());
                        endDate = SmsQuotaDateUtils.dateFormatDay(smsTrendQueryVO.getEndTime());
                        Integer monthLimit = SmsQuotaDateUtils.diffMonths(smsTrendQueryVO.getBeginTime(), smsTrendQueryVO.getEndTime());
                        smsTrendList = msgHandleLogMapper.queryMonthTrend(smsTrendQueryVO.getMsgSourceId(), beginDate, endDate, monthLimit);
                    } else {
                        logger.info("事件间隔小于等于90天，按天查询");
                        beginDate = SmsQuotaDateUtils.dateFormatDay(smsTrendQueryVO.getBeginTime());
                        endDate = SmsQuotaDateUtils.tomorrowFormat(smsTrendQueryVO.getEndTime());
                        tempEndDate = SmsQuotaDateUtils.dateFormatDay(smsTrendQueryVO.getEndTime());
                        smsTrendList = msgHandleLogMapper.queryDayTrend(smsTrendQueryVO.getMsgSourceId(), beginDate, endDate, tempEndDate);
                    }
                    break;
                default:
                    logger.info("未匹配到查询类型");
                    smsTrendList = new ArrayList<>();
                    break;
            }
        }

        resultVO.setSmsTrends(smsTrendList);
        Integer successCount = smsTrendList.stream().mapToInt(SmsTrendResultVO.SmsTrend::getSuccess).sum();
        Integer failCount = smsTrendList.stream().mapToInt(SmsTrendResultVO.SmsTrend::getFail).sum();
        String rate = "0";
        if (successCount != 0) {
            double ratio = (double) successCount / (successCount + failCount);
            NumberFormat format = NumberFormat.getPercentInstance();
            //设置保留几位小数
            format.setMaximumFractionDigits(2);
            rate = format.format(ratio);
        }
        resultVO.setSuccessCount(successCount);
        resultVO.setFailCount(failCount);
        resultVO.setRate(rate);
        return resultVO;
    }

}
